package deployr.core;

import static deployr.core.Slurp.*;

import java.io.*;

public class MavenRepository implements ScanListener {

	private final MavenIndex index = new MavenIndex();

	public MavenRepository(final File repository) {
		new Scan(this, repository);
	}

	public void discovered(final File root, final File file) {
		if (isPom(file)) {
			indexPom(root, file);
		}
		if (isJarSha1(file)) {
			indexJarSha1(root, file);
		}
	}

	public void discovered(final String path, final String md5) {}

	public MavenIndex getIndex() {
		return index.newIndex();
	}

	public void remove(final String path) {}

	private void indexJarSha1(final File root, final File file) {
		final String relativePath = relativePath(root, file);
		final String sha1 = slurp(new File(root, relativePath)).substring(0, 40);
		final String path = withoutJarSha1(relativePath);
		index.sha1(path, sha1);
	}

	private void indexPom(final File root, final File file) {
		final String relativePath = relativePath(root, file);
		final String pom = slurp(new File(root, relativePath));
		final String artifact = new Pom(pom).artifact().toString();
		final String path = withoutPom(relativePath);
		index.artifact(path, artifact);
	}

	private boolean isJarSha1(final File file) {
		return file.getName().endsWith(".jar.sha1");
	}

	private boolean isPom(final File file) {
		return file.getName().endsWith(".pom");
	}

	private String relativePath(final File root, final File file) {
		return file.getAbsolutePath().replaceAll(root.getAbsolutePath(), "").replaceAll("^/+", "");
	}

	private String withoutJarSha1(final String relativePath) {
		return relativePath.replaceAll(".jar.sha1$", "");
	}

	private String withoutPom(final String relativePath) {
		return relativePath.replaceAll(".pom$", "");
	}
}
